package dian.qing.li.demo.security.utils;


import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import java.nio.charset.Charset;

@UtilityClass
public class Base64Utils {
    public static final Charset UTF_8 = Charset.forName("UTF-8");
    public static final Charset GBK = Charset.forName("GBK");
    public static final String EMPTY_STRING = "";

    /**
     * 编码
     *
     * @param source 源码
     * @return
     */
    public static String encode(String source) {
        if (StringUtils.isBlank(source)) {
            return EMPTY_STRING;
        }
        return new String(new Base64().encode(source.getBytes(UTF_8)), UTF_8);
    }

    /**
     * 指定字符集-编码
     *
     * @param source 源码
     * @return
     */
    public static String encode(String source, Charset charset) {
        if (StringUtils.isBlank(source)) {
            return EMPTY_STRING;
        }
        return new String(new Base64().encode(source.getBytes(charset)));
    }

    /**
     * 解码
     *
     * @param code 密文
     * @return
     */
    public static byte[] decode(String code) {
        return new Base64().decode(code);
    }
}
